import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import DiaryView from '../views/DiaryView.vue'
import DiaryCreateView from '../views/DiaryCreateView.vue'
import EmotionAnalysisView from '../views/EmotionAnalysisView.vue'
import RelaxationView from '../views/RelaxationView.vue'
import ResourcesView from '../views/ResourcesView.vue'
import AboutView from '../views/AboutView.vue'
import AuthView from '../views/AuthView.vue'
import ChatView from '../views/ChatView.vue'
import UserCenterView from '../views/UserCenterView.vue'
import MemberCenterView from '../views/MemberCenterView.vue'

// 路由守卫：检查是否登录
function requireAuth(to, from, next) {
  const user = localStorage.getItem('user')
  if (user) {
    // 用户已登录，继续访问
    next()
  } else {
    // 用户未登录，重定向到登录页面
    next({ path: '/auth', query: { redirect: to.fullPath } })
  }
}

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView,
    beforeEnter: requireAuth
  },
  {
    path: '/chat',
    name: 'chat',
    component: ChatView
  },
  {
    path: '/auth',
    name: 'auth',
    component: AuthView
  },
  {
      path: '/diary',
      name: 'diary',
      component: DiaryView,
      beforeEnter: requireAuth
    },
    {
      path: '/diary/create',
      name: 'diary-create',
      component: DiaryCreateView,
      beforeEnter: requireAuth
    },
    {
      path: '/emotion-analysis',
      name: 'emotion-analysis',
      component: EmotionAnalysisView,
      beforeEnter: requireAuth
    },
    {
      path: '/relaxation',
      name: 'relaxation',
      component: RelaxationView,
      beforeEnter: requireAuth
    },
    {
      path: '/resources',
      name: 'resources',
      component: ResourcesView,
      beforeEnter: requireAuth
    },
  {
    path: '/about',
    name: 'about',
    component: AboutView,
    beforeEnter: requireAuth
  },
  {
    path: '/user-center',
    name: 'user-center',
    component: UserCenterView,
    beforeEnter: requireAuth
  },
  {
    path: '/member-center',
    name: 'member-center',
    component: MemberCenterView,
    beforeEnter: requireAuth
  },
  // 默认重定向到登录页面
  {
    path: '/:pathMatch(.*)*',
    redirect: '/auth'
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 导航守卫，实现登录保护
router.beforeEach((to, from, next) => {
  // 检查用户是否已登录（从localStorage获取）
  const isLoggedIn = localStorage.getItem('user') !== null;
  
  // 如果访问的是登录页面
  if (to.path === '/auth') {
    // 如果已登录，重定向到首页
    if (isLoggedIn) {
      next('/');
    } else {
      // 如果未登录，允许访问登录页面
      next();
    }
  } else {
    // 如果访问的是其他页面
    if (isLoggedIn) {
      // 如果已登录，允许访问
      next();
    } else {
      // 如果未登录，重定向到登录页面
      next('/auth');
    }
  }
})

export default router